package swardToOffer.method_2_sort_or_find.find;

/**
 * @Author ChanZany
 * @Date 2021/5/26 9:15
 * @Version 1.0
 * <p>
 * 面试题53（二）：0到n-1中缺失的数字
 * 题目：一个长度为n-1的递增排序数组中的所有数字都是唯一的，并且每个数字
 * 都在范围0到n-1之内。在范围0到n-1的n个数字中有且只有一个数字不在该数组
 * 中，请找出这个数字。
 */
public class MissingNumber {

    public int missingNumber2(int[] nums) {
        int left = 0, right = nums.length - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (nums[mid]==mid) left=mid+1;
            else right=mid-1;
        }
        return left;
    }

    public int missingNumber(int[] nums) {
        if (nums.length <= 0) return 0;
        int left = 0, right = nums.length - 1;
        return helper(nums, left, right);
    }

    private int helper(int[] nums, int left, int right) {
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] != mid) { //缺省的元素就是Mid或者在mid左边
                if (mid == 0 || nums[mid - 1] == mid - 1) {
                    return mid;
                }
                right = mid - 1;
            } else left = mid + 1;
        }
        if (left == nums.length) return nums.length;
        return -1;
    }


    public static void main(String[] args) {
        MissingNumber Main = new MissingNumber();
        int[] nums = new int[]{0, 1, 2, 4, 5};
        System.out.println(Main.missingNumber(nums));
    }
}
